package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.mapper.SearchHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author pengyehua
 * @date 2020/12/9 19:12
 */

/**
 * 搜索模块
 */
@Service
public class WxSearchServiceImpl implements WxSearchService{

    @Autowired
    KeywordMapper keywordMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    /**
     * 搜索关键词索引
     * @return
     */
    @Override
    public SearchIndex queryIndex(Integer userId) {
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andIsDefaultEqualTo(true);
        List<Keyword> defaultKeywords = keywordMapper.selectByExample(keywordExample);

        KeywordExample keywordExample1 = new KeywordExample();
        KeywordExample.Criteria criteria1 = keywordExample1.createCriteria();
        criteria1.andIsHotEqualTo(true);
        List<Keyword> hotKeywords = keywordMapper.selectByExample(keywordExample1);

        SearchIndex searchIndex = new SearchIndex();
        searchIndex.setDefaultKeyword(defaultKeywords.get(0));
        searchIndex.setHotKeywordList(hotKeywords);

        if (userId != null){
            List<HistoryKeyword> historyKeywords = searchHistoryMapper.selectKeyword(userId,false);
            searchIndex.setHistoryKeywordList(historyKeywords);
        }
        return searchIndex;
    }

    /**
     * 删除搜索历史
     */
    @Override
    public void updateSearchHistory(Integer userId) {
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setDeleted(true);
        searchHistoryMapper.updateByExampleSelective(searchHistory,searchHistoryExample);
    }

    /**
     * 搜索关键字
     * @param keyword
     * @return
     */
    @Override
    public List<String> queryKeyword(String keyword) {
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andKeywordLike("%" + keyword + "%");
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);

        List<String> strings = new ArrayList<>();
        for (Keyword keyword1 : keywords) {
            strings.add(keyword1.getKeyword());
        }
        return strings;
    }
}
